package com.mars.basic.controller.admincontroller;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.google.common.collect.Maps;
import com.mars.basic.allmain.entity.AdminRoleEntity;
import com.mars.basic.allmain.entity.AdminUserEntity;
import com.mars.basic.allmain.entity.RoleEntity;
import com.mars.basic.allmain.po.*;
import com.mars.basic.allmain.vo.AdminRoleVo;
import com.mars.basic.allmain.vo.RoleIdsVo;
import com.mars.basic.allmain.vo.RolePermissionVo;
import com.mars.basic.service.AdminRoleService;
import com.mars.basic.service.AdminUserService;
import com.mars.basic.service.RolePermissionService;
import com.mars.basic.service.RoleService;
import com.mars.common.expetion.Code;
import com.mars.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/adminUser")
public class AdminController {
    @Autowired
    private AdminRoleService adminRoleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/addRoleForAdmin")
    public R addRoleForAdmin(@RequestBody AdminRoleVo vo) {
        QAssert.isTrue(adminRoleService.check(vo), Code.ENTITY_EXIST_EXCEPTION, "该用户已添加过该角色");
        adminRoleService.getAdminRoleRepository().save(vo.build());
        return R.ok();
    }

    @RequestMapping("/addPermissionForRole")
    public R addPermissionForRole(@RequestBody RolePermissionVo vo) {
        QAssert.isTrue(rolePermissionService.check(vo), Code.ENTITY_EXIST_EXCEPTION, "该角色已具备此权限，请勿重复操作");
        RolePermission rolePermission = vo.build();
        rolePermissionService.getRepository().save(rolePermission);
        return R.ok();
    }

    @RequestMapping("/{adminId}/updateAdminRoles")
    public R updateAdminRole(@RequestBody RoleIdsVo vo, @PathVariable Integer adminId) {
        List<AdminRoleEntity> dataAdminRoles = adminRoleService.findAdminRoleByAdminId(adminId);
        AdminUserEntity adminUserEntity = adminUserService.getAdminUserRepository().findById(adminId).orElse(null);
        List<Integer> newIds = vo.getRoleIds();
        //删除取消关联的关联信息
        List<AdminRoleEntity> needDeletedAdminRoles = dataAdminRoles.stream()
                .filter(o -> !newIds.contains(o.getAdminId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(needDeletedAdminRoles) && needDeletedAdminRoles.size() > 0) {
            adminRoleService.getAdminRoleRepository().deleteAll(needDeletedAdminRoles);
        }

        List<Integer> needSaveIds = newIds.stream()
                .filter(o -> !dataAdminRoles.stream().mapToInt(AdminRoleEntity::getRoleId).boxed().collect(Collectors.toList()).contains(o))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(needSaveIds) && needSaveIds.size() > 0) {
            List<RoleEntity> roleEntities = roleService.getRoleRepository().findAll(QRole.role.id.in(needSaveIds));
            HashMap<String, RoleEntity> map = Maps.newHashMap();
            for (RoleEntity roleEntity : roleEntities) {
                map.put(String.valueOf(roleEntity.getId()), roleEntity);
            }
            List<AdminRole> needSaveAdminRoles = needSaveIds.stream().map(q -> {
                AdminRole adminRole = AdminRoleEntity.builder()
                        .adminId(adminId)
                        .updateTime(new Date())
                        .createTime(new Date())
                        .adminName(adminUserEntity.getName())
                        .roleName(map.get(String.valueOf(q)).getName())
                        .status(MarsConstant.StatusEnum.ENABLE.value())
                        .roleId(q)
                        .build();
                return adminRole;
            }).collect(Collectors.toList());
            adminRoleService.getAdminRoleRepository().saveAll(needSaveAdminRoles.stream().map(o -> Beans.mapper(o, AdminRoleEntity.class)).collect(Collectors.toList()));
        }
        return R.ok();
    }

    @RequestMapping("/{adminId}/getRolesInAdmin")
    public R getRolesInAdmin(@PathVariable Integer adminId) {
        List<Role> roles = adminRoleService.findRolesByAdminId(adminId);
        return R.data(roles);
    }

}
